<template>
    <div id="app">
		<p>
	        <el-input type="text" placeholder="请输入你的名字" v-model="loginName" />
	        <el-button @click="login()">登录</el-button>
			<el-button @click="close_ws()">关闭</el-button>
	    </p>
	    <p>
	        <el-input placeholder="" v-model="message" v-on:keydown.enter.native="sendMessage()"/>
	    </p>
		<el-input ref=textarea type="textarea" v-model="messageList" name="" id="textarea_id" cols="30" rows="10"></el-input>
	</div>
</template>

<script>
export default {
    data(){
        return{
            ws:null,
            ws_url:'ws://10.31.7.46:9999/websocket/chat/',
            loginName:"",
            message:"",
            messageList:""
        }
    },
    methods:{
        login(){
            //debugger
            this.ws = new WebSocket(this.ws_url + this.loginName);
            //ws = new WebSocket("ws://10.2.33.14:8080/websocket");
            // 建立 web socket 连接成功触发事件
            this.ws.onopen = this.onopen;
            // 接收服务端数据时触发事件
            this.ws.onmessage = this.onmessage;
            // 断开 web socket 连接成功触发事件
            this.ws.onclose = this.onclose;
            
            this.ws.onerror = this.onerror;
        },
        sendMessage() {
            if (this.message != '') {
                this.ws.send(this.message);
                this.message ='';
            }
        },
        onopen() {
            this.log_message('Info: WebSocket 连接成功.');
        },
        onmessage (evt) {
            //debugger
            var received_msg = evt.data;
            this.log_message(received_msg);
        },
        onclose () {
            this.log_message('Info: WebSocket 关闭.');
        },
        onerror () {
            this.log_message('Info: WebSocket 出现错误.');
        },
        log_message(msg){
            this.messageList = this.messageList+"\r\n" + msg;
            const textarea = document.getElementById('textarea_id');
            textarea.scrollTop = textarea.scrollHeight;
        },
        close_ws(){
            //debugger
            alert("close");
            this.ws.close();
        }
    },
    created:function () {
        console.log("created");
    },
    mounted:function () {
        console.log("mounted start");
    }
}
</script>
<style>

</style>


